package com.hlcl.huaji.view;

import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.elcl.activity.BaseActivity;
import com.elcl.util.DateUtil;
import com.elcl.util.ListUtils;
import com.elcl.util.StringUtils;
import com.elcl.util.viewutils.WindowUtils;
import com.elcl.widget.comp.toast.ToastUtils;
import com.elcl.widget.view.flowlayout.FlowLayout;
import com.elcl.widget.view.flowlayout.FlowLayoutUtil;
import com.elcl.widget.view.flowlayout.TagRecourse;
import com.google.gson.reflect.TypeToken;
import com.hlcl.huaji.R;
import com.hlcl.huaji.model.CommentCreateOrderInfoBean;
import com.hlcl.huaji.model.CommentDetail;
import com.hlcl.huaji.model.CommentDetailResponse;
import com.hlcl.huaji.model.CommentGetOrderInfoBean;
import com.hlcl.huaji.model.Label;
import com.hlcl.huaji.model.LabelResponse;
import com.hlcl.huaji.model.LabelResult;
import com.hlcl.huaji.model.Order;
import com.hlcl.huaji.server.NetCode;
import com.hlcl.huaji.server.OrderServer;
import com.hlcl.huaji.utils.MyTagView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lichunlin on 2018/6/17.
 * 评论界面
 */

public class CommentActivity extends BaseActivity {

    private Order order;
    private FlowLayout flow_bottom;
    private MyTagView tag_view_bottom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_comment);

        flow_bottom = findViewById(R.id.flow_bottom);
        tag_view_bottom = findViewById(R.id.tag_view_bottom);
        rb_comment_bottom = findViewById(R.id.rb_comment_bottom);
        edt_comment = findViewById(R.id.edt_comment);

        order = (Order) getIntent().getSerializableExtra("order");
        if (null != order) {
            initOrderView();
            getConfingLabel();
        } else {
            ToastUtils.showToast("获取订单信息失败");
            finish();
        }

        WindowUtils windowUtils = new WindowUtils();
        windowUtils.fullScreen(CommentActivity.this);
    }

    private RatingBar rb_comment_bottom;
    private EditText edt_comment;

    //获取标签的label
    private void getConfingLabel() {
        OrderServer.getInstance().getConfingLabel(netHandler);
    }

    private void initOrderView() {
        setText(R.id.tv_order_state, order.getRepairResult() == 1 ? "维修成功" : "维修失败");
        setText(R.id.tv_order_date, "下单时间:" + DateUtil.getDateFormat(order.getOrderTime(), DateUtil.YYYY_MM_DD_HH_MM));
        setText(R.id.tv_order_no, "订单编号:" + order.getOrderid());
        setText(R.id.tv_order_state, "接单时间：" + order.getOrderGetDate());

        if (order.getRepairResult() == 1) {//维修成功
            setText(R.id.tv_order_state_judge, "维修评价");
        } else if (order.getRepairResult() == 2) {//维修失败
            setText(R.id.tv_order_state_judge, "维修失败解决方案及反馈");
        }
    }

    //获取订单评论的
    private void getOrderCommentServer() {
        OrderServer.getInstance().getOrderComment(netHandler, order.getOrderid());
    }

    private LabelResponse labelResponse;

    @Override
    protected void praseJson(int reqId, String json) {
        if (reqId == NetCode.ID_COMMENT_GET) {//获取订单状态
            CommentDetailResponse commentDetailResponse = gson.fromJson(json, new TypeToken<CommentDetailResponse>() {
            }.getType());
            if (null != commentDetailResponse) {
                CommentDetail commentDetail = commentDetailResponse.getjData();
                if (null != commentDetail) {//如果评论不为空
                    CommentCreateOrderInfoBean commentCreateOrderInfoBean = commentDetail.getCommentCreateOrderInfo();
                    CommentGetOrderInfoBean commentGetOrderInfoBean = commentDetail.getCommentGetOrderInfo();
                    if (null != commentCreateOrderInfoBean && commentCreateOrderInfoBean.getCommentId() != 0) {//如果上面的评论不为空的话，显示
                        initTopCommentView(commentCreateOrderInfoBean);
                    } else {
                        setVisibility(R.id.ll_comment_create, View.GONE);
                    }

                    if (null != commentGetOrderInfoBean && commentGetOrderInfoBean.getCommentId() != 0) {//如果是下面的评论不为空，就只是展示
                        initBottomCommentView(commentGetOrderInfoBean);
                    } else {
                        initBottomAddCommentView();
                    }
                }
            }
        } else if (reqId == NetCode.ID_LABEL_GET) {//获取标签的内容
            LabelResult labelResult = gson.fromJson(json, new TypeToken<LabelResult>() {
            }.getType());
            if (null != labelResult) {
                labelResponse = labelResult.getjData();
                getOrderCommentServer();
            } else {
                ToastUtils.showToast("获取标签内容失败");
            }
        } else if (reqId == NetCode.ID_COMMENT_ADD) {//添加评论
            ToastUtils.showToast("评论成功");
            setResult(RESULT_OK);
            finish();
        }
    }

    private void initTopCommentView(CommentCreateOrderInfoBean commentCreateOrderInfoBean) {
        setVisibility(R.id.ll_comment_create, View.VISIBLE);
        setText(R.id.tv_name, order.getOrder_get_user_name());
        setText(R.id.tv_date_comment, "下单时间:" + DateUtil.getDateFormat(order.getCommentTime(), DateUtil.YYYY_MM_DD_HH_MM));
        MyTagView myTagViewTop = findViewById(R.id.tag_view_top);
        List<String> stringList = getPicListByString(commentCreateOrderInfoBean.getLabel_name());
        initTagView(stringList, myTagViewTop);

        RatingBar rb_comment_top = findViewById(R.id.rb_comment_top);
        rb_comment_top.setStepSize(0.5f);
        rb_comment_top.setNumStars(5);
        rb_comment_top.setMax(5);
        rb_comment_top.setRating(commentCreateOrderInfoBean.getScore());
    }

    private void initTagView(List<String> groupTagAlls, MyTagView tag_view) {
        if (ListUtils.isNotEmpty(groupTagAlls)) {
            tag_view.setVisibility(View.VISIBLE);
            tag_view.removeAllViews();
            tag_view.setGravity(Gravity.CENTER_HORIZONTAL);
            for (int i = 0; i < groupTagAlls.size(); i++) {
                final String tagName = groupTagAlls.get(i);
                View view = LayoutInflater.from(this).inflate(R.layout.view_tag_simple, null);
                TextView tv_label = view.findViewById(R.id.tv_label);
                tv_label.setText(tagName);

                tag_view.addView(view);
            }
        }
    }

    //将返回的图片的string转换为list<String>
    private List<String> getPicListByString(String picShow) {
        List<String> list_pic = new ArrayList<>();
        if (StringUtils.isNotBlank(picShow)) {
            String[] picShows = picShow.split(",");
            if (null != picShows) {
                for (int i = 0; i < picShows.length; i++) {
                    list_pic.add(picShows[i]);
                }
            } else {
                list_pic.add(picShow);
            }
        }
        return list_pic;
    }

    /****************底部的评价按钮(如果是已经评论的话)****************/
    private void initBottomCommentView(CommentGetOrderInfoBean commentGetOrderInfoBean) {
        //设置tagview的内容
        if (null != commentGetOrderInfoBean) {
            List<String> list_comment = getPicListByString(commentGetOrderInfoBean.getLabelName());
            tag_view_bottom.setVisibility(View.VISIBLE);
            initTagView(list_comment, tag_view_bottom);
        }

        //设置评分
        rb_comment_bottom.setStepSize(0.5f);
        rb_comment_bottom.setNumStars(5);
        rb_comment_bottom.setMax(5);
        rb_comment_bottom.setRating(commentGetOrderInfoBean.getScore());

        //设置评价的内容
        edt_comment.setText(commentGetOrderInfoBean.getComment_content());
        edt_comment.setCursorVisible(false);
        edt_comment.setFocusable(false);
        edt_comment.setFocusableInTouchMode(false);
        edt_comment.setBackgroundColor(getResources().getColor(R.color.trans));

        setVisibility(R.id.btn_add, View.GONE);
    }

    /****************底部的评价添加的按钮****************/
    private List<Label> labelsSelected = new ArrayList<>();

    private void initBottomAddCommentView() {
        labelsSelected.clear();
        if (null != labelResponse) {
            if (order.getRepairResult() == 1) {//维修成功
                labelsSelected = labelResponse.getLable2();
            } else if (order.getRepairResult() == 2) {//维修失败
                labelsSelected = labelResponse.getLable3();
            }

            for (int i = 0, len = labelsSelected.size(); i < len; i++) {
                Label label = labelsSelected.get(i);
                label.setTitle(label.getLableName());
                label.setOut_id(label.getLableId() + "");
                labelsSelected.set(i, label);
            }

            initBottomTagView();
            setListener(R.id.btn_add, new View.OnClickListener() {//点击添加
                @Override
                public void onClick(View v) {
                    startCommentServer();
                }
            });
        }
    }

    private FlowLayoutUtil flowLayoutUtil;

    public void initBottomTagView() {
        flow_bottom.setVisibility(View.VISIBLE);

        TagRecourse tagRecourse = new TagRecourse();
        tagRecourse.setColorPressed(getResources().getColor(R.color.color_yellow));
        tagRecourse.setColorUnPressed(getResources().getColor(R.color.trans));
        tagRecourse.setColorTxtPressed(getResources().getColor(R.color.white));
        tagRecourse.setColorTxtUnPressed(getResources().getColor(R.color.text_grey));
        tagRecourse.setStrokeColorPressed(getResources().getColor(R.color.trans));
        tagRecourse.setStrokeColorUnPressed(getResources().getColor(R.color.trans));
        flowLayoutUtil = new FlowLayoutUtil(flow_bottom, tagRecourse);

        flowLayoutUtil.initFlowLayout(labelsSelected);
    }

    //开始评价
    private void startCommentServer() {
        int score = rb_comment_bottom.getNumStars();

        String commentContent = edt_comment.getText().toString().trim();//获取评论内容

        String[] nameAndId = getCommentNameAndId();
        if (null != nameAndId) {
            OrderServer.getInstance().addComment(netHandler, order.getOrderid(), score, nameAndId[0], nameAndId[1], commentContent);
        } else {
            ToastUtils.showToast("请选择标签");
        }
    }


    //获取评论的相关内容
    private String[] getCommentNameAndId() {
        String[] content = new String[2];
        if (null != flowLayoutUtil) {
            List<Label> labels = flowLayoutUtil.getIsCheckedTag();
            if (ListUtils.isEmpty(labels)) {
                content = null;
            } else {
                String labelName = "";
                String labelId = "";
                for (int i = 0, len = labels.size(); i < len; i++) {
                    if (i == 0) {
                        labelName = labels.get(i).getLableName();
                        labelId = labels.get(i).getLableId() + "";
                    } else {
                        labelName = labelName + "," + labels.get(i).getLableName();
                        labelId = labelId + "," + labels.get(i).getLableId() + "";
                    }
                    content[0] = labelId;
                    content[1] = labelName;
                }
            }
        }
        return content;
    }


}
